import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
// pages/evaluateGift/myPrice/myPrice.js

const app = getApp();
import { Index } from '../../../apis/index';
import util from '../../../utils/util';
const API = new Index();
const url = require('../../../apis/api');
WXPage({
  /**
   * 页面的初始数据
   */
  data: {
    // hotelAdd: ['请选择省市区', '', ''],
    imageList: [],
    imgUrl: '',
    array: ['携程', '美团', '同程', '飞猪旅行', '抖音'],
    addList: [],
    defaultImg: '/static/zhongman2/img_Coupon@2x.png',
    imageUrl: `${app.globalData.imageUrl}/zhongman2`,
    host: wx.getStorageSync("host"),
    dataIndex: 0,
    thirdOrder: ''
  },
  setInputData(e) {
    let key = e.target.dataset.key
    this.setData({ [key]: e.detail.value })
  },
  // 进入页面加载
  onLoad(e) {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FFFFFF'
    });
    // 先获取商品
    let id = JSON.parse(e.id);
    let param = {
      "id": id
    };
    API.getPraiseDetail(param).then(res => {
      if (!res.result.icon) {
        var imgUrl = this.data.defaultImg;
      } else {
        var imgUrl = this.data.host + res.result.icon;
      }
      this.setData({
        res: res.result,
        imgUrl: imgUrl
      });
    });

    // 获取房间号
    this.getroomNum();
  },
  onShow() {
    // 获取地址
    let id = this.data.id;
    this.getAddressList(id);
    // 获取登录
    this.getLoginToken();
  },
  updateImg(e) {
    this.setData({
      imageList: e.detail
    });
  },
  // 获取登录信息的手机号
  getLoginToken() {
    API.getLoginToken().then(res => {
      if (!res) return;
      let loginInfo = res.result;
      this.setData({
        phone: loginInfo.phone
      });
      wx.setStorageSync("login_key", loginInfo);
    });
  },
  // 获取房间号和设备号
  getroomNum() {
    let param = {
      "deviceSn": app.globalData.deviceSn
    };
    API.getDeviceInfo(param).then(res => {
      app.setBluetoothMac(res.result.bluetoothMac);
      wx.setStorageSync("baseInfo", res.result);
      this.setData({
        devInfo: res.result
      });
    });
  },
  // 联系人 省市区控件
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    });
  },
  // 地址
  getAddressList: function (e) {
    API.addressList().then(res => {
      let addressDetails = {}
      let addressId = wx.getStorageSync('addressId') || 0
      console.log(`wx.getStorageSync('addressId') || 0`, addressId)
      for(let item of res.result || []) if(Number(item.id) === Number(addressId)) {
        addressDetails = item
        break
      }
      this.setData({addList: res.result, addressDetails});
    });
    // API.getAddressDetails({
    //   id: Number(e)
    // }).then(res => {
    //   const data = res.result;
    //   this.setData({
    //     addressDetails: data
    //   });
    // });
  },
  //普通选择器：
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    });
  },
  // // 酒店 省市区控件
  // bindHotelChange: function (e) {
  //   this.setData({
  //     hotelAdd: e.detail.value
  //   })
  // },
  // 跳转到物品详情
  gotoDetail() {
    wx.navigateTo({
      url: '/pages/evaluateGift/priceDetail/priceDetail' + '?id=' + this.data.res.id
    });
  },
  // 填写收货人
  writeConsignee: function (url) {
    let info = {
      id: this.data.id || null
    };
    url = '/pages/evaluateGift/myPrice/mypriceAddress/mypriceAddress' + '?info=' + JSON.stringify(info);
    wx.navigateTo({
      url
    });
  },
  // 上传图片
  uploadImgFileFn(tempFilePath, loginInfo) {
    wx.uploadFile({
      url: app.globalData.apiUrl + '/upload',
      filePath: tempFilePath,
      name: 'file',
      formData: {
        'openid': loginInfo.openid
      },
      header: {
        'content-type': 'multipart/form-data',
        'Access-Token': 'dingo ' + loginInfo.token
      },
      fail: res => {},
      success: res => {
        if (res.statusCode === 401) return wx.navigateTo({
          url: '/pages/serviceHome/serviceHome'
        });
        let data = JSON.parse(res.data);
        let imageList = this.data.imageList;
        imageList.push(data.result);
        this.setData({
          imageList
        });
      }
    });
  },
  // 上传图片
  changeImage() {
    let that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let loginInfo = wx.getStorageSync('login_key');
        for (let tempFilePath of res.tempFilePaths || []) this.uploadImgFileFn(tempFilePath, loginInfo);
        // tempFilePath可以作为img标签的src属性显示图片
        // const tempFilePaths = res.tempFilePaths
        // let imageList = that.data.imageList
        // imageList = imageList.concat(tempFilePaths)
        // that.setData({imageList})
      }
    });
  },

  // 删除照片
  deleteImg(e) {
    let index = e.currentTarget.dataset.i;
    let imageList = this.data.imageList;
    imageList.splice(index, 1);
    this.setData({
      imageList
    });
  },
  // 弹窗地址
  // 遮罩层显示
  show: function () {
    this.setData({
      flag: false
    });
  },
  // 遮罩层隐藏
  conceal: function () {
    this.setData({
      flag: true
    });
  },
  // 跳转到抽奖页面
  toDraw(item) {
    wx.redirectTo({
      url: `/pages/evaluateGift/draw/index?id=${item.commentId}&nId=${item.notificationId}`
    });
  },
  // 提交
  submit: function (e) {
    let imgStrArray = this.data.imageList;
    // let addressId = "";

    if (this.data.res.type === 3 && !this.data.addList[0]) {
      wx.showToast({
        title: '请填写地址',
        icon: 'none'
      });
      return false;
    }
    if (this.data.thirdOrder == null) {
      wx.showToast({
        title: '请填写酒店下单时的订单号',
        icon: 'none'
      });
      return false;
    }
    // 商品如果库存为0，显示已下架
    // if (this.data.res.num == 0) {
    //   wx.showToast({
    //     title: '该商品库存已空',
    //     icon: 'none'
    //   })
    //   return false
    // }
    if (!this.data.array[this.data.index]) {
      wx.showToast({
        title: '请选择下单平台',
        icon: 'none'
      });
      return false;
    }
    if (imgStrArray.length == 0) {
      wx.showToast({
        title: '请上传截图',
        icon: 'none'
      });
      return false;
    }
    // type === 3 实体物品
    // type === 1 || type === 2 优惠券
    let addressId;
    const {
      addressDetails,
      addList,
      res
    } = this.data;
    if (res.type === 1 || res.type === 2) {
      addressId = 0;
    } else if (addList.length > 0) {
      console.log('addressDetails', addressDetails);
      const addressDetailId = addressDetails.id;
      const addListId = addList[0].id;
      addressId = addressDetailId ? addressDetailId : addListId;
    }
    console.log('addressId==>', addressId);
    var param = {};
    let appName = this.data.array[this.data.index];
    let phone = this.data.phone || this.data.addressDetails.phone;
    if(!phone && this.data.addList[0]) phone = this.data.addList[0].phone
    // let addressId = this.data.addressDetails.id || this.data.addList[0].id || 0
    param.placeId = this.data.devInfo.placeId;
    // param.goodsId = this.data.res.id
    param.placeName = this.data.devInfo.placeName;
    param.addressId = addressId;
    param.placeRoom = this.data.devInfo.room;
    param.deviceSn = this.data.devInfo.deviceSn;
    param.appName = appName;
    param.thirdOrder = this.data.thirdOrder;
    param.imgStrArray = imgStrArray;
    param.phone = phone;
    API.getPrice(param).then(res => {
      if (!res.result) return wx.showToast({
        title: '提交失败，请稍后重试',
        duration: 600
      });
      this.toDraw(res.result);
      // wx.showToast({
      //   title: '提交成功',
      //   duration: 600
      // })
      // setTimeout(function () {
      //   wx.redirectTo({
      //     url: '/pages/evaluateGift/myPrice/success/success',
      //   })
      // }, 800)
    });
  },

  toKeFu: function () {
    // wx.reportEvent("event_hp_kf", {});
    wx.navigateTo({
      url: '/pages/mine/zmKf/zmkf'
    });
  },
  toHaoPing: function () {
    // wx.reportEvent("event_hp_help", {});
    wx.navigateTo({
      url: '/pages/mine/zmHp/zmhp'
    });
  }
});
